package com.woniu.adopt.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.adopt.entity.Manager;
import com.woniu.adopt.entity.Permission;
import com.woniu.adopt.entity.Role;
import com.woniu.adopt.mapper.ManagerMapper;
import com.woniu.adopt.mapper.PermissionMapper;
import com.woniu.adopt.mapper.RoleMapper;
import com.woniu.adopt.vo.RecycleVo;
import com.woniu.adopt.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    ManagerMapper managerMapper;
    @Autowired
    PermissionMapper permissionMapper;


    public PageInfo<Role> queryByPage(Integer now, Integer size, String name) {
        PageHelper.startPage(now, size);

        List<Role> roles = roleMapper.selectRoleByName(name);

        return new PageInfo<>(roles);
    }

    public Role queryRoleByKey(int id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public int add(Role role) {
        return roleMapper.insert(role);
    }

    public int modify(Role role) {
        return roleMapper.updateByPrimaryKey(role);
    }

    @Transactional
    public int removeBykey(Long id) {
        //1. 解除用户绑定的角色
        roleMapper.deleteManagerRoleByRoleId(id);
        //2.解除 权限绑定的角色
        roleMapper.deleteRolePermissionByRoleId(id);
        //3.删除角色
        int i = roleMapper.deleteByPrimaryKey(id);
        return i;
    }

    @Transactional
    public void authority(RoleVo roleVo) {
        // 1. 先删除 当前角色的所有权限
        roleMapper.deleteRolePermissionByRoleId(roleVo.getId());
        // 2. 插入新的权限
        roleMapper.insertPermissionByRole(roleVo.getId(), roleVo.getPerCheckedIds());
    }

    public List<Role> queryAllRole() {
        return roleMapper.selectAll();
    }

    public List<RecycleVo> selectRecycle() {
        return roleMapper.selectRecycle();
    }


    public int doRecycle(int id, String type) {
        if ("role".equals(type)) {
            return roleMapper.doRecycle(id);
        } else if ("type".equals(type)) {
            return managerMapper.doRecycle(id);
        } else {
            return permissionMapper.doRecycle(id);
        }
    }
}
